package erfgame.core.graphics.renderer;


import erfgame.core.CompassDirection;
import erfgame.core.Rotation;
import erfgame.core.entity.Entity;
import erfgame.core.entity.EntityEvent;
import erfgame.core.entity.EntityEventType;
import erfgame.core.entity.EntityListener;
import erfgame.core.entity.Orientable;


public class OrientableEntityRendererDelegate extends AbstractEntityRendererProxy implements EntityListener {

	private EntityRenderer[] orientationRenderers;
	private Orientable orientable;
	private Rotation viewRotation;
	
	public OrientableEntityRendererDelegate(EntityRenderer[] orientationRenderers, Orientable orientable, Rotation viewRotation) {
		this.orientationRenderers = orientationRenderers;
		this.orientable = orientable;
		this.viewRotation = viewRotation;
		reloadOrientation();
	}

	@Override
	public void start() {
		this.getEntity().addEntityListener(EntityEventType.orientation, this);
		reloadOrientation();
		super.start();
		
	}

	public void entityChanged(Entity source, EntityEvent event) {
		reloadOrientation();
	}
	
	private void reloadOrientation() {
		CompassDirection orientation = viewRotation.rotate(orientable.getOrientation());
		int arrayIndex;
		if( orientation != null ) {
			arrayIndex = (orientation.getArrayIndex())%orientationRenderers.length;
		} else {
			arrayIndex = 0;
		}
		this.setProxied(orientationRenderers[arrayIndex]);
	}
}
